<template>
  <div class="q-pa-md bg-white row">
    <div class="col-xl-6 col-lg-6 col-sm-6 col-xs-12">
      <q-form ref="dataForm" class="q-pa-sm dialog-form-container">
        <ul>
          <li style="display: flex;">
            <span>
              用户名
            </span>
            <span>
              <q-input outlined dense v-model="tempData.username" @blur="updateData('user')" />
            </span>
          </li>
          <!-- <li>
            <span>
              报告中名称
            </span>
            <span>
              <q-input
                outlined
                dense
                v-model="tempData.report_name"
              />
            </span>
          </li> -->
          <li style="display: flex;">
            <span>
              电话
            </span>
            <span>
              <q-input outlined dense v-model="tempData.telephone" @blur="updateData()" />
            </span>
          </li>
          <li style="display: flex;">
            <span>
              邮箱
            </span>
            <span>
              <q-input outlined dense v-model="tempData.email" @blur="updateData" />
            </span>
          </li>
          <li style="display: flex;">
            <span>
              密码
            </span>
            <span>
              <q-btn class="q-mr-sm q-mt-xs borderRadius" unelevated style="width: 200px;" padding="8px 8px 7px"
                color="primary" label="修改密码" @click="handleModify" />
            </span>
          </li>
        </ul>
      </q-form>
    </div>
    <div class="col-xl-6 col-lg-6 col-sm-6 col-xs-12 form-right-container ">
      <div v-show="!isBinding" class="qr-code">
        <p>请用微信扫描绑定账号关联</p>
        <div id="qrcode" ref="qrCodeDiv" />
      </div>

      <ul v-show="isBinding" class="img-container">
        <li v-for="itemImg in personInfo" :key="itemImg.id" class="every-img">
          <p v-show="itemImg.is_binding" class="nick-name-p">{{ itemImg.nickname }}</p>
          <img v-if="itemImg.is_binding" :src="itemImg.headimgurl" alt="">
          <q-btn v-show="itemImg.is_binding" class="q-mr-sm q-mt-xs borderRadius" style="display: block;" icon="search"
            unelevated padding="8px 8px 7px" color="primary" label="解除绑定" @click="removeBound(itemImg.id)" />
        </li>
      </ul>
    </div>
    <!-- 添加/编辑 弹出对话框 -->
    <q-dialog v-model="dialogPassVisible" persistent>
      <q-card class="card-style">
        <!-- 对话框的头部 -->
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">修改密码</div>
          <q-space />
          <q-btn icon="close" flat round dense @click="dialogPassVisible = false"></q-btn>
        </q-card-section>
        <!-- 对话框的主体-->
        <q-card-section>
          <q-form ref="rulePassForm" class="q-pa-sm dialog-form-container">
            <ul>
              <li>
                <span>
                  <span style="color: red">*</span>
                  旧密码
                </span>
                <span>
                  <q-input outlined dense v-model="ruleForm.pwd" :rules="rules.pwd"
                    :type="oldisPwd ? 'password' : 'text'">
                    <template v-slot:append>
                      <q-icon :name="oldisPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer"
                        @click="oldisPwd = !oldisPwd" />
                    </template>
                  </q-input>
                  <!-- <q-input outlined dense v-model="ruleForm.pwd" :rules="rules.pwd" /> -->
                </span>
              </li>
              <li>
                <span>
                  <span style="color: red">*</span>
                  新密码
                </span>
                <span>
                  <q-input outlined dense v-model="ruleForm.new_pwd" :rules="rules.new_pwd"
                    :type="isPwd ? 'password' : 'text'">
                    <template v-slot:append>
                      <q-icon :name="isPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer"
                        @click="isPwd = !isPwd" />
                    </template>
                  </q-input>
                  <!-- <q-input outlined dense v-model="ruleForm.new_pwd" lazy-rules bottom-slots :rules=rules.new_pwd /> -->
                </span>
              </li>
              <li>
                <span>
                  <span style="color: red">*</span>
                  重复新密码
                </span>
                <span>
                  <q-input outlined dense v-model="ruleForm.re_new_pwd" :rules="rules.re_new_pwd"
                    :type="isPwd2 ? 'password' : 'text'">
                    <template v-slot:append>
                      <q-icon :name="isPwd2 ? 'visibility_off' : 'visibility'" class="cursor-pointer"
                        @click="isPwd2 = !isPwd2" />
                    </template>
                  </q-input>
                  <!-- <q-input outlined dense v-model="ruleForm.re_new_pwd" :rules="rules.re_new_pwd" /> -->
                </span>
              </li>

            </ul>
          </q-form>
        </q-card-section>
        <!-- 对话框的底部 -->
        <q-card-actions align="right">
          <q-btn unelevated label="取消" type="reset" style="color: #686868;" outline
            @click="dialogPassVisible = false" />
          <q-btn unelevated label="确定" type="submit" color="accent" @click="modifyPass" />
        </q-card-actions>
      </q-card>
    </q-dialog>

  </div>
</template>

<script>
import { fetchOwnerInfo, updateOwnerInfo, modifyPass, fetchWxInfo, removeWxBound, fetchWxQrCodeInfo } from '../../../../api/personAdmini'
import QRCode from 'qrcodejs2'
import { ref } from 'vue'

export default {
  setup() {
    return {
      oldisPwd: ref(true),
      isPwd: ref(true),
      isPwd2: ref(true),
    }
  },
  data() {
    return {
      userId: localStorage.getItem('user_id_GFYW'),
      tempData: {
        username: '',
        telephone: '',
        email: ''
      },
      dialogPassVisible: false,
      ruleForm: {
        pwd: '',
        new_pwd: '',
        re_new_pwd: ''
      },
      rules: {
        username: [val => val && val.length > 0 || '请输入用户名'],
        telephone: [val => val && val.length > 0 || '请输入电话'],
        'pwd': [val => val && val.length > 0 || '请输入密码'],
        'new_pwd': [val => val && val.length > 0 || '请再次输入密码'],
        're_new_pwd': [val => val && val.length > 0 || '请确认新密码'],
      },
      reChPasswordType: 'password',
      newPasswordType: 'password',
      againPasswordType: 'password',
      personInfo: [{ is_binding: false }],
      personTotal: 0,
      isBinding: false,
      qrCodeUrl: ''
    }
  },
  beforeUnmount() {
    clearTimeout(this.isLoopTimer)
    this.isLoopTimer = null
  },
  created() {
    this.getSingleInfo()
    this.getPersonWx()
    this.getQrCode()
  },
  methods: {
    // 获取人员微信信息
    getPersonWx() {
      const wxInfo = {
        uid: localStorage.getItem('user_id_GFYW'),
        is_binding: true
      }
      fetchWxInfo(wxInfo).then(res => {
        if (res.status === 200) {
          this.personInfo = res.data
          this.personTotal = res.totalCounts

          // 判断是否需要保持长连接，以便于监测用户是否已经扫描二维码
          if (this.personInfo.length <= 0 || !this.personInfo[0].is_binding) {
            if (this.isLoopTimer) {
              clearTimeout(this.isLoopTimer)
              this.isLoopTimer = null
            }
            this.isLoopTimer = setTimeout(() => {
              this.getPersonWx()
            }, 2000)
          } else {
            clearTimeout(this.isLoopTimer)
            this.isLoopTimer = null
            this.isBinding = true
          }
        }
      })
    },
    // 获取二维码内容
    getQrCode() {
      fetchWxQrCodeInfo({ uid: localStorage.getItem('user_id_GFYW') }).then(res => {
        if (res.status === 200) {
          this.qrCodeUrl = res.data.url
          this.$nextTick(() => {
            // 生成二维码
            new QRCode(this.$refs.qrCodeDiv, {
              text: this.qrCodeUrl,
              width: 132,
              height: 132,
              colorDark: '#333333', // 二维码颜色
              colorLight: '#ffffff', // 二维码背景色
              correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
            })
          })
        }
      })
    },
    // 解除微信绑定
    removeBound(id) {
      this.isBinding = false
      removeWxBound(id, { is_binding: this.isBinding }).then(res => {
        if (res.status === 200) {
          this.getPersonWx()
        }
      })
    },

    getSingleInfo() {
      const listQu = { uid: this.userId }
      fetchOwnerInfo(listQu).then(res => {
        if (res.status === 200) {
          this.tempData = res.data[0]
        }
      })
    },
    // 保存编辑的内容
    updateData(val) {
      updateOwnerInfo(this.tempData, this.userId).then(res => {
        this.$q.notify({
          position: 'top',
          message: '更新成功',
          type: 'positive'
        })
        if (val && val === 'user') {
          this.$store.dispatch('login/logoutFun')
          // this.$store.commit('app/SET_VISITED_VIEWS') //  清空可见tab标签
          this.$router.push({
            path: '/login',
            query: {
              change_username: 'true'
            }
          })
        } else {
          this.getSingleInfo()
        }
      })
    },

    // 重置修改密码
    resetRuleForm() {
      this.ruleForm = {
        pwd: '',
        new_pwd: '',
        re_new_pwd: ''
      }
    },
    // 修改密码
    handleModify() {
      this.dialogPassVisible = true
      this.resetRuleForm()
      this.ruleForm.uid = this.userId
      this.$nextTick(() => {
        this.$refs['rulePassForm'].resetValidation()
      })
    },
    modifyPass() {
      this.$refs['rulePassForm'].validate().then(valid => {
        if (valid) {
          modifyPass(this.ruleForm).then(res => {
            if (res.status === 200) {
              if (res.hasOwnProperty('request_data')) {
                this.dialogPassVisible = false
                this.$q.notify({
                  position: 'top',
                  message: '密码修改成功！',
                  type: 'positive'
                })
              } else {
                this.$q.notify({
                  position: 'top',
                  message: res.data.msg,
                  type: 'negative'
                })
              }
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.form-right-container {
  .img-container {
    list-style: none;
    padding: 0;
    margin: 0;
    // width: 600px;
    overflow: auto;
    list-style: none;
    padding: 0;

    .every-img {
      width: 136px;
      white-space: nowrap;
      float: left;
      display: block;

      .nick-name-p {
        text-align: center;
      }

      .remove-bound {
        margin-top: 5px;
        width: 132px;
        display: block;
      }
    }
  }

  .qr-code {
    #qrcode {
      margin-left: 28px;
    }
  }
}

// 弹出的对话框样式
.dialog-form-container {
  ul {
    li {
      overflow: hidden;
      min-height: 42px;
      line-height: 42px;
      margin-bottom: 15px;

      >span {
        display: inline-block;

        &:first-child {
          margin-right: 10px;
          width: 100px;
        }

        &:last-child {
          width: 200px;
        }
      }
    }
  }
}

@media (max-width: 600px) {
  .every-img {
    margin: 0 auto;
    float: none !important;
  }
}
</style>
